﻿using Abp.Runtime.Session;
using Hicap.AuthorizationServer.Core.Common.EFCore;
using Hicap.AuthorizationServer.Core.Models;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Hicap.AuthorizationServer.Core.Managers
{
    public class AuthObjectRoleRelatedManager : ManagerBase<AuthObjectRoleRelated>, IAuthObjectRoleRelatedManager
    {
        private readonly IUserRoleRelatedManager _userRoleRelatedManager;

        public AuthObjectRoleRelatedManager(IUnitOfWork unitOfWork, IAbpSession session
        , IUserRoleRelatedManager userRoleRelatedManager) : base(unitOfWork)
        {
            _userRoleRelatedManager = userRoleRelatedManager;

            QueryCondition.Add(x => x.IsDeleted == false);
            CreateActions.Add(x => x.CreatorUserId = session.UserId);
            CreateActions.Add(x => x.CreationTime = DateTime.Now);
            UpdateActions.Add(x => x.LastModificationTime = DateTime.Now);
            UpdateActions.Add(x => x.LastModifierUserId = session.UserId);
            DeleteActions.Add(x => x.DeletionTime = DateTime.Now);
            DeleteActions.Add(x => x.DeleterUserId = session.UserId);
            DeleteActions.Add(x => x.IsDeleted = true);

            CreateCheckActions.Add(x =>
            {
                if (x.Id == 0) return true;
                Log.Warning($"AuthObjectRoleRelated CreateCheck Fail : {JsonConvert.SerializeObject(x)}");
                return false;
            });
            UpdateCheckActions.Add(x =>
            {
                if (x.Id > 0 && x.IsDeleted == false) return true;
                Log.Warning($"AuthObjectRoleRelated UpdateCheck Fail : {JsonConvert.SerializeObject(x)}");
                return false;
            });
            DeleteCheckActions.Add(x =>
            {
                if (x.IsDeleted == false) return true;
                Log.Warning($"AuthObjectRoleRelated DeleteCheck Fail : {JsonConvert.SerializeObject(x)}");
                return false;
            });
        }

        //记录数
        public async Task<int> GetCount(Func<AuthObjectRoleRelated, bool> query)
        {
            return await Repository.CountAsync(x => query(x));
        }

        //查询结果
        public async Task<List<AuthObjectRoleRelated>> GetResult(Func<AuthObjectRoleRelated, bool> query)
        {
            return await Repository.GetIncludingQuery(x => x.Role, x => x.AuthObject).Where(x => query(x)).ToListAsync();
        }

        public List<AuthObject> GetAuthRole(List<Role> roles)
        {
            List<AuthObject> auths = Repository.GetIncludingQuery(x => x.Role, x => x.AuthObject)
               .AsNoTracking()
               .Where(x => roles.Select(y => y.Id).Any(y => x.Role.Id == y))
               .Select(x => x.AuthObject).ToList();
            return auths;
        }
    }
}